package zhuyun.code.launcheractivity.view.fragment

import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.PopupWindow
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.bumptech.glide.Glide
import kotlinx.android.synthetic.main.fragment_home.*
import kotlinx.android.synthetic.main.fragment_home.view.*
import kotlinx.android.synthetic.main.pup_qrcode.view.*

import zhuyun.code.launcheractivity.R
import zhuyun.code.launcheractivity.model.NetworkRequest
import zhuyun.code.launcheractivity.model.ResponseDataHandler
import zhuyun.code.launcheractivity.model.data.*
import zhuyun.code.launcheractivity.view.MainActivity
import zhuyun.code.launcheractivity.view.ScanQRCodeActivity
import zhuyun.code.launcheractivity.view.adapter.HomeProductListAdapter
import zhuyun.code.launcheractivity.view.adapter.HomeRecommendProductListAdapter
import zhuyun.code.launcheractivity.view.adapter.HomeTwoProductListAdapter
import zhuyun.code.launcheractivity.view.adapter.StarUserFollowAdapter
import zhuyun.code.launcheractivity.view.listener.PermissionListener
import zhuyun.code.launcheractivity.view.widget.component.ImageLoaderInferface


/**
 * A simple [Fragment] subclass.
 * Use the [HomeFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class HomeFragment : Fragment(),View.OnClickListener {

    private lateinit var contentView:View




    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment

         contentView = inflater.inflate(R.layout.fragment_home, container, false)
        initView()
        return contentView

    }

    private val startUserFollowBeanList = mutableListOf<StarUserFollwBean>()
    private lateinit var starUserFollowAdapter: StarUserFollowAdapter
    private val productListBeanList= mutableListOf<ProductListBean>()
    private lateinit var productListAdapter:HomeProductListAdapter
    private val recProductListBeanList = mutableListOf<RecProductListBean>()
    private lateinit var recommendProductListAdapter:HomeRecommendProductListAdapter
    private val twoProductListBeanList = mutableListOf<RecProductTwoListBean>()
    private lateinit var twoProductListAdapter:HomeTwoProductListAdapter

    private fun initView(){
        starUserFollowAdapter = StarUserFollowAdapter(startUserFollowBeanList)
        contentView.rvRecommendFollow.layoutManager = LinearLayoutManager(activity,LinearLayoutManager.HORIZONTAL,false)
        contentView.rvRecommendFollow.adapter = starUserFollowAdapter

        productListAdapter = HomeProductListAdapter(productListBeanList)
        contentView.rvNewProject.layoutManager = LinearLayoutManager(activity,RecyclerView.HORIZONTAL,false)
        contentView.rvNewProject.adapter = productListAdapter

        recommendProductListAdapter = HomeRecommendProductListAdapter(recProductListBeanList)
        contentView.rvRecommend.layoutManager = LinearLayoutManager(activity,RecyclerView.HORIZONTAL,false)
        contentView.rvRecommend.adapter = recommendProductListAdapter

        twoProductListAdapter = HomeTwoProductListAdapter(twoProductListBeanList)
        contentView.rvTwoProject.layoutManager = LinearLayoutManager(activity,RecyclerView.HORIZONTAL,false)
        contentView.rvTwoProject.adapter = twoProductListAdapter
        contentView.ibQR.setOnClickListener(this)

        contentView.refreshLayout.setOnRefreshListener { getHomeData() }


        getHomeData()
    }

    private fun getHomeData(){
        NetworkRequest.getHomeData(object :ResponseDataHandler<HomeBean>(){
            override fun onSuccess(resultData: HomeBean?, baseResponse: BaseResponse<HomeBean>) {
                if(contentView.refreshLayout != null&&contentView.refreshLayout.isRefreshing){
                    refreshLayout.isRefreshing = false
                }
                val bannerImageUrls = mutableListOf<String>()
                resultData?.AdvInfos?.forEach { bannerImageUrls.add(it.IconURL) }

                banner.setImages(bannerImageUrls).setImageLoader(object :ImageLoaderInferface<ImageView>{
                    override fun displayImage(
                        context: Context,
                        path: String?,
                        imageView: ImageView
                    ) {
                        Glide.with(context).load(path).into(imageView)
                    }

                    override fun createImageView(context: Context): ImageView? {
                        return null

                    }

                }).setAutoPlay(true).start()

                //推荐关注
                if(resultData!!.StarUserFollw!=null){
                    startUserFollowBeanList.clear()
                    startUserFollowBeanList.addAll(resultData!!.StarUserFollw)
                    starUserFollowAdapter.notifyDataSetChanged()
                    contentView.rlRecommendFollow.visibility = if(resultData.StarUserFollw.isEmpty()) View.GONE else View.VISIBLE
                    contentView.rvRecommendFollow.visibility = if(resultData.StarUserFollw.isEmpty()) View.GONE else View.VISIBLE
                }
                //最新商品
                if(resultData!!.ProductList != null){
                    productListBeanList.clear()
                    productListBeanList.addAll(resultData.ProductList)
                    productListAdapter.notifyDataSetChanged()
                    contentView.rlNewProject.visibility=if(resultData.ProductList.isEmpty()) View.GONE else View.VISIBLE
                    contentView.rvNewProject.visibility=if(resultData.ProductList.isEmpty()) View.GONE else View.VISIBLE

                }
                //推荐商品
                if(resultData!!.RecProductList!=null){
                    recProductListBeanList.clear()
                    recProductListBeanList.addAll(resultData.RecProductList)
                    recommendProductListAdapter.notifyDataSetChanged()
                    contentView.rlRecommend.visibility=if(resultData.RecProductList.isEmpty()) View.GONE else View.VISIBLE
                    contentView.rvRecommend.visibility=if(resultData.RecProductList.isEmpty()) View.GONE else View.VISIBLE
                }
                //全球订票
                val videoBannerImgs = mutableListOf<String>()
                resultData.VideoAdvInfos.forEach {
                    videoBannerImgs.add(it.IconURL)
                }
                rlBuyTicket.visibility = if(videoBannerImgs.isEmpty()) View.GONE else View.VISIBLE
                videoBanner.visibility = if(videoBannerImgs.isEmpty()) View.GONE else View.VISIBLE
                if(videoBannerImgs.isNotEmpty()){
                    videoBanner.setImages(videoBannerImgs).setImageLoader(object :ImageLoaderInferface<ImageView>{
                        override fun displayImage(
                            context: Context,
                            path: String?,
                            imageView: ImageView
                        ) {
                            Glide.with(imageView.context).load(path).into(imageView)
                        }

                        override fun createImageView(context: Context): ImageView? {
                            return null
                        }

                    }).setAutoPlay(true).start()
                }
                //广告
                val advList = mutableListOf<String>()
                resultData.StarVideoAdv.forEach {
                    advList.add(it.AdvImg)
                }
                rlAdVideo.visibility = if(advList.isEmpty()) View.GONE else View.VISIBLE
                adBanner.visibility = if(advList.isEmpty()) View.GONE else View.VISIBLE
                if(advList.isNotEmpty()){
                    adBanner.setImages(advList).setImageLoader(object :ImageLoaderInferface<ImageView>{
                        override fun displayImage(
                            context: Context,
                            path: String?,
                            imageView: ImageView
                        ) {
                            Glide.with(imageView.context).load(path).into(imageView)
                        }

                        override fun createImageView(context: Context): ImageView? {
                            return null
                        }

                    }).setAutoPlay(true).start()
                }

                //闲置产品
                if(resultData.RecProductTwoList != null){
                    twoProductListBeanList.clear()
                    twoProductListBeanList.addAll(resultData.RecProductTwoList)
                    twoProductListAdapter.notifyDataSetChanged()
                    contentView.rlTwoProject.visibility = if(resultData.RecProductTwoList.isEmpty()) View.GONE else View.VISIBLE
                    contentView.rvTwoProject.visibility = if(resultData.RecProductTwoList.isEmpty()) View.GONE else View.VISIBLE
                }

            }

            override fun onFailure(errMsg: String?) {
                Toast.makeText(activity,errMsg,Toast.LENGTH_SHORT).show()
                contentView.refreshLayout.isRefreshing = false
            }

        })
    }

    private val qrcodePupWindow:PopupWindow by lazy {
        val popView = LayoutInflater.from(activity).inflate(R.layout.pup_qrcode,null)
        val popupWindow = PopupWindow(popView,ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT,true)
        popupWindow.isOutsideTouchable = true
        popupWindow.contentView.tvScaningCode.setOnClickListener(this)
        popupWindow.contentView.tvRideCode.setOnClickListener(this)
        popupWindow
    }

    private val cameraPermissions = arrayOf<String>("android.permission.WRITE_EXTERNAL_STORAGE", "android.permission.CAMERA", "android.permission.READ_EXTERNAL_STORAGE")

    override fun onClick(v: View?) {
        when(v?.id){
            R.id.ibQR->{
                qrcodePupWindow.showAsDropDown(contentView.ibQR,-contentView.ibQR.width,0)
            }
            R.id.tvScaningCode->{
                qrcodePupWindow.dismiss()
                (activity as MainActivity).requestPermissions(cameraPermissions,object :PermissionListener{
                    override fun onGranted() {
                        startActivity(Intent(activity,ScanQRCodeActivity::class.java))
                    }

                    override fun onDenied(deniedPermissions: List<String>) {

                    }

                })

            }
            R.id.tvRideCode->{

            }

        }

    }


}
